package BFS.FloodFill算法;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 正难则反: 被包围的区域: <a href="https://leetcode.cn/problems/surrounded-regions/description/">...</a>
 */
public class likou130 {

    // 利用bfs
    int[] dx = new int[]{0, 0, 1, -1};
    int[] dy = new int[]{1, -1, 0, 0};
    boolean[][] vis = new boolean[201][201]; // 题目总共300 * 300个岛屿
    int m , n;
    public void solve(char[][] board) {
        // 需要多次 bfs
        m = board.length; n = board[0].length;

        // 1. 先处理边界情况的0. 变为和其他不一样的 字符?
        // 先处理上下两行
        for (int j = 0; j < n; j++) {
            if(board[0][j] == 'O') bfs(board, 0, j);
            if(board[m - 1][j] == 'O') bfs(board, m - 1, j);
        }
        //处理左右边界两列
        for (int i = 0; i < m; i++) {
            if(board[i][0] == 'O') bfs(board, i, 0);
            if(board[i][n - 1] == 'O') bfs(board, i, n - 1);
        }
        // 2. 遍历原数组进行还原
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if(board[i][j] == 'O') board[i][j] = 'X';
                else if(board[i][j] == '?') board[i][j] = 'O';
            }
        }
    }

    private void bfs(char[][] grid, int i, int j) {
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{i, j});
        // vis[i][j] = true; // 标记已经访问过 这里要修改原数组, 所以不用标记数组了
        grid[i][j] = '?';

        // bfs 主逻辑
        while(!queue.isEmpty()) {
            int[] poll = queue.poll(); // 弹出栈顶
            int a = poll[0], b = poll[1];

            // 加入下一层
            for (int k = 0; k < 4; k++) {
                int x = a + dx[k], y = b + dy[k];
                if(x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 'O') {
                    queue.offer(new int[]{x, y});
                    grid[x][y] = '?'; // 先修改为 字符 ?
                }
            }
        }
    }

}
